<template>
	<div class="city-map-wrap">

		<template v-if="inWhiteList">
			<!-- 搜索框 -->
			<SearchInfo @query="query" :pageState="pageState"></SearchInfo>

			<!-- 核心指标 卡片 -->
			<Core @selectCard="selectCard" :pageState="pageState" v-loading="pageState.cardLoading" />

			<!-- 地图 -->
			<div class="map-container">
				<MapPannel ref="MapPannelTpl" class="pannel" @hotTypeChange="hotTypeChange" @indicateChange="indicateChange"
					:pageState="pageState" @setCenter="setCenter" @setMapZoom="setMapZoom" @setSelected="setSelected" />

				<Map ref="mapTpl" @showBusinessModal="showBModal" :markers="pageState.markers"
					:largeMarkers="pageState.largeMarkers" :clusterMarker="pageState.clusterMarker"
					:polygonPath="pageState.polygonPath" :pageState="pageState">
				</Map>
			</div>

			<!-- 详情表格 -->
			<DistrictDrawer ref="drawerTpl" :visible.sync="drawerVisible" :pageState="pageState" />

			<!-- 商圈信息 modal  -->
			<BusinessModal ref="busTpl" :visible.sync="isVisible" @checkDetail="showDrawer" :pageState="pageState" />
		</template>

		<no-power v-else :show-home="false"
			:friend-tips="'权限申请流程：满帮家-流程中心-权限申请-申请系统“数据平台/轨迹平台（conan）”链接：https://case.amh-group.com/csp/#/permission/apply'" />

	</div>
</template>

<script>

import moment from 'moment';
import Map from "./components/map.vue"
import Core from "./components/core-card.vue"
import MapPannel from "./components/pannel.vue"
import SearchInfo from "./components/search-info.vue"
import UrbanService from "@/service/urban-map.service"
import DistrictDrawer from "./modal/detail-table-drawer.vue"
import BusinessModal from "./modal/business-district-modal.vue"

const getCores = () => {
	return [
		{ label: '发货量', id: 1, value: 0, weekValue: 0, dayValue: 0, desc: '按照货源的装货地址归属，包含所有的货源' },
		{ label: '完单量', id: 2, value: 0, weekValue: 0, dayValue: 0, desc: '按照货源的装货地址归属，包含正常结束的所有订单' },
		{ label: '司机数', id: 3, value: 0, weekValue: 0, dayValue: 0, desc: 'APP定位数据，司机最后一次定位数据' },
		{ label: '货主数', id: 4, value: 0, weekValue: 0, dayValue: 0, desc: 'APP定位数据，货主最后一次定位数据' },
		{ label: '停留司机次数', id: 5, value: 0, weekValue: 0, dayValue: 0, desc: 'APP定位数据，司机停留时长超过20分钟的次数' },
		{ label: '停留司机人数', id: 6, value: 0, weekValue: 0, dayValue: 0, desc: 'APP定位数据，停留时长超过20分钟的司机人数' },
	]
}

export default {
	name: 'UrbanMap',
	components: {
		Map,
		Core,
		MapPannel,
		SearchInfo,
		BusinessModal,
		DistrictDrawer,
	},
	computed: {
		inWhiteList() {
			return this.$auth('conan-city_map');
		}
	},
	data() {
		return {
			isVisible: false,
			drawerVisible: false,

			pageState: {
				// core-card.vue
				cores: getCores(),
				cardLoading: false,
				selectedCardId: 1,

				// pannel.vue
				indicate: ['1'],
				hotType: 2,
				businessData: [],
				businessLoading: false,

				// map
				markers: [],
				largeMarkers: [],
				clusterMarker: [],
				polygonPath: [],
				uuid: undefined,

				// modal
				selectedObj: {},

				// search-info.vue
				searchForm: {
					provName: '江苏省', // 江苏 320000
					cityName: '南京市', // 南京 320100
					countyName: '雨花台区', // 雨花台 320114
					searchDate: moment().subtract(1, 'day'),
					compareDate: moment().subtract(2, 'day'),
				},
			}
		}
	},
	async mounted() {
		// 试图确保, 地图加载完成之后, 在执行查询
		this.$nextTick(() => {
			this.query();
		})
	},

	methods: {
		async query() {
			await this.getCoreIndicator()
			await this.getBussinessTop();
			this.queryMapData();
		},

		setCenter(gis) {
			this.$refs.mapTpl.setMapCenter(gis);
		},

		setMapZoom(level) {
			this.$refs.mapTpl.setMapZoom(level);
		},

		setSelected(polygon) {
			this.$refs.mapTpl.setSelected(polygon);
		},

		indicateChange() {
			this.getMapPoi();
		},

		hotTypeChange() {
			// 1: 热力图, 2: 点状图
			if (this.pageState.hotType === 1) {
				this.$refs.mapTpl.drawHeatMap();
			} else {
				this.$refs.mapTpl.addClusterMarker();
			}
		},

		async getCoreIndicator() {
			try {
				this.pageState.cardLoading = true;
				const params = {
					provName: this.pageState.searchForm.provName,
					cityName: this.pageState.searchForm.cityName,
					countyName: this.pageState.searchForm.countyName,
					searchDate: moment(this.pageState.searchForm.searchDate).format("YYYYMMDD"),
					compareDate: moment(this.pageState.searchForm.compareDate).format("YYYYMMDD"),
				}
				const data = await UrbanService.coreIndicators(params);
				if (data) {
					this.transformData(data);
				} else {
					this.pageState.cores = getCores();
				}
			} catch (error) {
				console.log(error);
			} finally {
				this.pageState.cardLoading = false;
			}

		},

		transformData(data = {}) {
			this.pageState.cores[0].value = data.cargoNum
			this.pageState.cores[0].weekValue = data.cargoNumWeekRate
			this.pageState.cores[0].dayValue = data.cargoNumDayRate

			this.pageState.cores[1].value = data.cargoCompleteNum
			this.pageState.cores[1].weekValue = data.cargoCompleteNumWeekRate
			this.pageState.cores[1].dayValue = data.cargoCompleteNumDayRate

			this.pageState.cores[2].value = data.driverNum
			this.pageState.cores[2].weekValue = data.driverNumWeekRate
			this.pageState.cores[2].dayValue = data.driverNumDayRate

			this.pageState.cores[3].value = data.shipperNum
			this.pageState.cores[3].weekValue = data.shipperNumWeekRate
			this.pageState.cores[3].dayValue = data.shipperNumDayRate

			this.pageState.cores[4].value = data.stayDriverNum
			this.pageState.cores[4].weekValue = data.stayDriverNumWeekRate
			this.pageState.cores[4].dayValue = data.stayDriverNumDayRate

			this.pageState.cores[5].value = data.stayDriver
			this.pageState.cores[5].weekValue = data.stayDriverWeekRate
			this.pageState.cores[5].dayValue = data.stayDriverDayRate
		},

		showBModal() {
			this.isVisible = true
			this.$nextTick(() => {
				this.$refs.busTpl.init();
			})
		},

		showDrawer() {
			this.drawerVisible = true
			this.$refs.drawerTpl.init();
		},

		async selectCard(card) {
			this.$refs.MapPannelTpl.setIndicateValue([card.id + '']);
			this.getBussinessTop();
			this.queryMapData();
		},

		async queryMapData() {
			try {
				this.$refs.mapTpl.initMapLoading = true;
				await this.getMapPoi();
				await this.getMapAoi();
			} catch (error) {
				console.log(error);
			} finally {
				this.$refs.mapTpl.initMapLoading = false;
			}
		},

		async getBussinessTop() {
			try {
				this.pageState.businessLoading = true;
				const params = {
					provName: this.pageState.searchForm.provName,
					cityName: this.pageState.searchForm.cityName,
					countyName: this.pageState.searchForm.countyName,
					searchDate: moment(this.pageState.searchForm.searchDate).format("YYYYMMDD"),
					indicatorType: this.pageState.indicate.join(',')
				}
				const data = await UrbanService.aoiList(params);
				this.pageState.businessData = data;
			} catch (error) {
				console.log(error);
			} finally {
				this.pageState.businessLoading = false;
			}

		},

		async getMapPoi() {
			this.pageState.clusterMarker = [];

			const params = {
				provName: this.pageState.searchForm.provName,
				cityName: this.pageState.searchForm.cityName,
				countyName: this.pageState.searchForm.countyName,
				searchDate: moment(this.pageState.searchForm.searchDate).format("YYYYMMDD"),
				types: this.pageState.indicate.join(',')
			}
			const data = await UrbanService.mapIndicators(params);

			const points = [
				'cargo_num_points',
				'cargo_complete_num_points',
				'driver_num_points',
				'shipper_num_points',
				'stay_driver_num_points',
				'stay_driver_points'
			]

			if (!data) {
				this.pageState.clusterMarker = [];
				return;
			}

			points.forEach(item => {
				if (data[item]) {
					const resultPoints = this.transformToMarkerData(data[item]);
					this.pageState.clusterMarker = resultPoints;
				}
			})
		},

		async getMapAoi() {
			try {
				this.pageState.polygonPath = [];

				const params = {
					provName: this.pageState.searchForm.provName,
					cityName: this.pageState.searchForm.cityName,
					countyName: this.pageState.searchForm.countyName,
				}
				const data = await UrbanService.mapPoints(params);
				const paths = [];
				if (Array.isArray(data)) {
					// 字符串格式, "|" 分割一组数据 ";" 分割一点数据
					data.forEach(item => {
						if (!item.aoi_edge_points) {
							return
						}
						item.aSet = (item.aoi_edge_points || '').split('|');
						item.aoi_edge = [];
						item.aSet.forEach(sub => {
							item.aoi_edge = this.transformToMarkerData(sub);
							paths.push({
								aoi_id: item.aoi_id,
								uuid: item.uuid,
								path: item.aoi_edge
							});
						})
					})

					data.forEach(item => {
						item.poi_edge = this.transformToMarkerData(item.poi_sets);
						paths.push({
							aoi_id: item.aoi_id,
							uuid: item.uuid,
							path: item.poi_edge,
						});
					})
					this.pageState.polygonPath = paths.filter(item => item.path.length > 2);
					// console.log('画多边形的数据-处理后的:', this.pageState.polygonPath);
				}
			} catch (error) {
				console.log(error);
				this.pageState.polygonPath = [];
			}
		},

		// 返回的经纬度,可能经度在前, 也可能纬度在前, 数据统一处理一下
		transformToMarkerData(data) {
			if (!data) {
				return [];
			}
			const pairs = data.split(';').filter(Boolean);; // 将字符串按照 ';' 分割成一组一组的坐标对
			const tempArr = pairs.map(item => item.split(','))
			const coordinates = tempArr.map(item => item.map(Number));
			const result = coordinates.map(item => [Math.max(item[0], item[1]), Math.min(item[0], item[1])]);
			return result;
		}
	}
}

</script>

<style lang="less" scoped>
.city-map-wrap {
	width: 100%;
	height: 100%;
	background-color: #f0f2f5;
	padding: 10px 20px;
}

.map-container {
	position: relative;

	.pannel {
		position: absolute;
		top: 30px;
		z-index: 1;
	}
}
</style>
